<template>
  <div class="chatInterface" @contextmenu.prevent="">
    <div class="scroll-view">
      <img
        v-if="history.loading"
        class="history-loaded"
        src="./images/loading.svg"
      />
      <div
        v-else
        :class="history.allLoaded ? 'history-loaded' : 'load'"
        @click="loadHistoryMessage(false)"
      >
        {{ history.allLoaded ? "已经没有更多的历史消息" : "点击获取历史消息" }}
      </div>

      <van-checkbox-group
        v-model="messageSelector.messages"
        @change="selectMessages"
      >
        <!--消息记录-->
        <div
          v-for="(message, index) in history.messages"
          :key="message.messageId"
          :name="message.messageId"
        >
          <!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
          <div class="time-lag">
            {{ renderMessageDate(message, index) }}
          </div>
          <div class="message-recalled" v-if="message.recalled">
            <div v-if="message.senderId != doctor_id">
              {{ friend.name }}撤回了一条消息
            </div>
            <div v-else class="message-recalled-self">
              <div>你撤回了一条消息</div>
              <span
                v-if="
                  message.type === 'text' &&
                  Date.now() - message.timestamp < 60 * 1000
                "
                @click="editRecalledMessage(message.payload.text)"
                >重新编辑</span
              >
            </div>
          </div>
          <div class="message-item" v-else>
            <div class="message-item-checkbox">
              <van-checkbox
                v-show="messageSelector.visible && message.status !== 'sending'"
                :name="message"
                :value="message.messageId"
              />
            </div>
            <div
              class="message-item-content"
              :class="{ self: message.senderId == doctor_id }"
            >
              <div class="avatar">
                <img
                  class="avatar"
                  :src="message.senderId == doctor_id ? avatar : friend.avatar"
                />
              </div>

              <div
                class="content"
                @click.right="showActionPopup(message)"
                @longpress="showActionPopup(message)"
              >
                <div class="message-payload">
                  <b class="pending" v-if="message.status === 'sending'"></b>
                  <b class="send-fail" v-if="message.status === 'fail'"></b>
                  <div
                    v-if="message.type === 'text'"
                    v-html="renderTextMessage(message)"
                  ></div>
                  <!-- <img
                    v-if="message.type === 'image'"
                    :data-url="message.payload.url"
                    :src="message.payload.url"
                    :style="{
                      height:
                        getImageHeight(
                          message.payload.width,
                          message.payload.height
                        ) + 'rpx',
                    }"
                    class="image-content"
                    mode="heightFix"
                    @click="showImageFullScreen"
                  /> -->
                  <img
                    v-if="message.type === 'image'"
                    :height="
                      getImageHeight(
                        message.payload.width,
                        message.payload.height
                      ) + 'px'
                    "
                    :src="message.payload.url"
                    @click="showImageFullScreen(message.payload.url)"
                    alt=""
                  />
                  <!-- <van-image
                    v-if="message.type === 'image'"
                    :height="
                      getImageHeight(
                        message.payload.width,
                        message.payload.height
                      ) + 'px'
                    "
                    fit="none"
                    :src="message.payload.url"
                    @click="showImageFullScreen(message.payload.url)"
                  /> -->
                  <div
                    class="video-snapshot"
                    v-if="message.type === 'video'"
                    :data-url="message.payload.video.url"
                    @click="playVideo"
                  >
                    <img
                      :height="
                        getImageHeight(
                          message.payload.width,
                          message.payload.height
                        ) + 'px'
                      "
                      :src="message.payload.url"
                      @click="showImageFullScreen(message.payload.url)"
                      alt=""
                    />
                    <!-- <van-image
                      :height="
                        getImageHeight(
                          message.payload.width,
                          message.payload.height
                        ) + 'px'
                      "
                      fit="contain"
                      :src="message.payload.url"
                    /> -->
                    <div class="video-play-icon"></div>
                  </div>
                  <div class="file-content" v-if="message.type === 'file'">
                    <div class="file-info">
                      <span class="file-name">{{ message.payload.name }}</span>
                      <span class="file-size"
                        >{{ (message.payload.size / 1024).toFixed(2) }}KB</span
                      >
                    </div>
                    <img class="file-img" src="./images/file-icon.png" />
                  </div>
                  <div
                    v-if="message.type === 'audio'"
                    class="audio-content"
                    @click="playAudio(message)"
                  >
                    <div
                      class="audio-facade"
                      :style="{
                        width:
                          Math.ceil(message.payload.duration) * 7 + 50 + 'px',
                      }"
                    >
                      <div
                        class="audio-facade-bg"
                        :class="{
                          'play-icon':
                            !audioPlayer.loading &&
                            audioPlayer.playingMessage &&
                            audioPlayer.playingMessage.messageId ===
                              message.messageId,
                        }"
                      ></div>
                      <div>
                        {{ Math.ceil(message.payload.duration) || 1
                        }}<span>"</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="message.type === 'order'" class="order-content">
                    <div class="order-id">订单号：{{ message.payload.id }}</div>
                    <div class="order-body">
                      <img :src="message.payload.url" class="order-img" />
                      <div>
                        <div class="order-name">{{ message.payload.name }}</div>
                        <div class="order-info">
                          <div class="order-price">
                            {{ message.payload.price }}
                          </div>
                          <div class="order-count">
                            共{{ message.payload.count }}件
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- <div
                  v-if="message.senderId == doctor_id"
                  :class="message.read ? 'message-read' : 'message-unread'"
                >
                  <div v-if="message.status === 'success'">
                    {{ message.read ? "已读" : "未读" }}
                  </div>
                </div> -->
              </div>
            </div>
          </div>
        </div>
      </van-checkbox-group>
    </div>
    <div
      class="action-box"
      v-if="!videoPlayer.visible && !messageSelector.visible"
    >
      <div class="action-top">
        <div class="more-box" @click="switchAudioKeyboard">
          <img class="more" v-if="audio.visible" src="./images/jianpan.png" />
          <img class="more" v-else src="./images/audio.png" />
        </div>
        <div
          v-if="audio.visible"
          class="record-input"
          @touchstart.stop.prevent="onRecordStart"
          @touchend.stop.prevent="onRecordEnd"
        >
          {{ audio.recording ? "松开发送" : "按住录音" }}
        </div>
        <!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
        <input
          v-else
          v-model="text"
          @confirm="sendTextMessage"
          class="consult-input"
          maxlength="700"
          placeholder="发送消息"
          type="text"
        />
        <div class="more-box" @click="switchEmojiKeyboard">
          <img class="more" v-if="emoji.visible" src="./images/jianpan.png" />
          <img class="more" v-else src="./images/emoji.png" />
        </div>
        <div class="more-box">
          <img
            @click="showOtherTypesMessagePanel()"
            class="more"
            src="./images/more.png"
          />
        </div>
        <div v-if="text" class="send-btn-box">
          <p class="btn" @click="sendTextMessage()">发送</p>
        </div>
      </div>
      <!--展示表情列表-->
      <div class="action-bottom action-bottom-emoji" v-if="emoji.visible">
        <img
          class="emoji-item"
          v-for="(emojiItem, emojiKey, index) in emoji.map"
          :key="index"
          :src="emoji.url + emojiItem"
          @click="chooseEmoji(emojiKey)"
        />
      </div>
      <!--其他类型消息面板-->
      <div v-if="otherTypesMessagePanelVisible" class="action-bottom">
        <van-uploader multiple accept="image" :beforeRead="beforeRead">
          <div class="more-icon">
            <img
              @click="sendImageMessage()"
              class="operation-icon"
              src="./images/picture.png"
            />
            <div class="operation-title">图片</div>
          </div>
        </van-uploader>
        <!-- <div class="more-icon">
          <img
            @click="sendVideoMessage()"
            class="operation-icon"
            src="./images/video.png"
          />
          <div class="operation-title">视频</div>
        </div>
        <div class="more-icon">
          <img
            @click="showOrderMessageList()"
            class="operation-icon"
            src="./images/order.png"
          />
          <div class="operation-title">订单</div>
        </div> -->
      </div>
    </div>
    <div
      class="action-popup"
      @touchmove.stop.prevent
      v-if="actionPopup.visible"
    >
      <div class="layer"></div>
      <div class="action-list">
        <div class="action-item" @click="deleteSingleMessage">删除</div>
        <div
          class="action-item"
          v-if="actionPopup.recallable"
          @click="recallMessage"
        >
          撤回
        </div>
        <div class="action-item" @click="showCheckBox">多选</div>
        <div class="action-item" @click="hideActionPopup">取消</div>
      </div>
    </div>
    <div class="messageSelector-box" v-if="messageSelector.visible">
      <img
        class="messageSelector-btn"
        @click="deleteMultipleMessages"
        src="./images/delete.png"
      />
    </div>
    <div class="record-loading" v-if="audio.recording"></div>
    <video
      v-if="videoPlayer.visible"
      :src="videoPlayer.url"
      id="videoPlayer"
      @fullscreenchange="onVideoFullScreenChange"
    ></video>
    <div v-if="orderList.visible" class="order-list">
      <div class="orders-content">
        <div class="title">
          <div>请选择一个订单</div>
          <div class="close" @click="hideOrderMessageList">×</div>
        </div>
        <div class="orders">
          <div
            v-for="(order, index) in orderList.orders"
            :key="index"
            class="order-item"
            @click="sendOrderMessage(order)"
          >
            <div class="order-id">订单号：{{ order.id }}</div>
            <div class="order-body">
              <img :src="order.url" class="order-img" />
              <div class="order-name">{{ order.name }}</div>
              <div class="order-right">
                <div class="order-price">{{ order.price }}</div>
                <div class="order-count">共{{ order.count }}件</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import EmojiDecoder from "./lib/EmojiDecoder";
import { parseTime } from "@/utils/tools.js";
import { ImagePreview } from "vant";
import Recorder from "js-audio-recorder";

const IMAGE_MAX_WIDTH = 200;
const IMAGE_MAX_HEIGHT = 150;
// const recorderManager = uni.getRecorderManager();
export default {
  name: "im",
  data() {
    const emojiUrl = "https://imgcache.qq.com/open/qcloud/tim/assets/emoji/";
    const emojiMap = {
      "[么么哒]": "emoji_3@2x.png",
      "[乒乓]": "emoji_4@2x.png",
      "[便便]": "emoji_5@2x.png",
      "[信封]": "emoji_6@2x.png",
      "[偷笑]": "emoji_7@2x.png",
      "[傲慢]": "emoji_8@2x.png",
    };
    return {
      //聊天文本框
      text: "",
      to: {}, // 作为createMessage的参数

      //定义表情列表
      emoji: {
        url: emojiUrl,
        map: emojiMap,
        visible: false,
        decoder: new EmojiDecoder(emojiUrl, emojiMap),
      },
      //是否展示‘其他消息类型面板’
      otherTypesMessagePanelVisible: false,
      orderList: {
        orders: [],
        visible: false,
      },
      history: {
        messages: [],
        allLoaded: false,
        loading: false,
      },
      audio: {
        startTime: null,
        //语音录音中
        recording: false,
        //录音按钮展示
        visible: false,
      },
      audioPlayer: {
        innerAudioContext: null,
        playingMessage: null,
        loading: false,
      },
      videoPlayer: {
        visible: false,
        url: "",
        context: null,
      },
      // 展示消息删除弹出框
      actionPopup: {
        visible: false,
        message: null,
        recallable: false,
      },
      // 消息选择
      messageSelector: {
        visible: false,
        messages: [],
      },
      friend: "",
      imgs: [],
      // 录音对象
      Recorder: null,
      RecorderPermission: false,
      // 录音强制结束的定时器,
      RecorderTimer: null,
      RecorderTimes: 60000,
    };
  },
  computed: {
    ...mapState("user", ["doctor_id", "doctor_name", "avatar"]),
  },
  created() {
    console.log(this);
    const friend = this.$route.query;
    this.friend = friend;
    this.to = {
      id: friend.id,
      type: this.GoEasy.IM_SCENE.PRIVATE,
      data: {
        name: friend.name,
        avatar: friend.avatar,
      },
    };
    this.$route.meta.title = friend.name;
    this.$setTitle(this.$route.meta.title);

    this.Recorder = new Recorder({
      sampleBits: 8, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 11025, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1, // 声道，支持 1 或 2， 默认是1
      // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
    });
    // this.videoPlayer.context = uni.createVideoContext("videoPlayer", this);
    // https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle
  },
  mounted() {
    //聊天对象
    this.connectGoEasy().then(() => {
      this.loadHistoryMessage(true);
      this.initialGoEasyListeners();
    });
    // 语音播放器
    this.initialAudioPlayer();
    // 录音监听器
    // this.initRecorderListeners();
  },
  // onshow() {
  //   this.otherTypesMessagePanelVisible = false;
  //   this.emoji.visible = false;
  // },
  // onPullDownRefresh(e) {
  //   this.loadHistoryMessage(false);
  // },
  beforeDestroy() {
    //退出聊天页面之前，清空监听器
    this.goEasy.im.off(
      this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED,
      this.onMessageReceived
    );
    this.goEasy.im.off(
      this.GoEasy.IM_EVENT.MESSAGE_DELETED,
      this.onMessageDeleted
    );
  },
  methods: {
    ...mapActions("message", ["connectGoEasy"]),
    //渲染文本消息，如果包含表情，替换为图片
    //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
    renderTextMessage(message) {
      return (
        '<span class="text-content">' +
        this.emoji.decoder.decode(message.payload.text) +
        "</span>"
      );
    },
    //像微信那样显示时间，如果有几分钟没发消息了，才显示时间
    //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
    renderMessageDate(message, index) {
      if (index === 0) {
        return parseTime(message.timestamp, "yy-mm-dd hh:ii");
      } else {
        if (
          message.timestamp - this.history.messages[index - 1].timestamp >
          5 * 60 * 1000
        ) {
          return parseTime(message.timestamp, "yy-mm-dd hh:ii");
        }
      }
      return "";
    },
    initialGoEasyListeners() {
      // 监听私聊消息
      this.goEasy.im.on(
        this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED,
        this.onMessageReceived
      );
      //监听消息删除
      this.goEasy.im.on(
        this.GoEasy.IM_EVENT.MESSAGE_DELETED,
        this.onMessageDeleted
      );
    },
    onMessageReceived(message) {
      let senderId = message.senderId;
      let receiverId = message.receiverId;
      let friendId = this.doctor_id == senderId ? receiverId : senderId;
      if (friendId == this.friend.id) {
        this.history.messages.push(message);
        //聊天时，收到消息标记为已读
        this.markPrivateMessageAsRead();
        //收到新消息，是滚动到最底部
        this.scrollToBottom();
      }
    },
    onMessageDeleted(deletedMessages) {
      deletedMessages.forEach((message) => {
        let senderId = message.senderId;
        let receiverId = message.receiverId;
        let friendId = this.doctor_id == senderId ? receiverId : senderId;
        if (friendId == this.friend.id) {
          let index = this.history.messages.indexOf(message);
          if (index > -1) {
            this.history.messages.splice(index, 1);
          }
        }
      });
    },
    audioPlayerOver() {
      console.log("播放结束");
      this.audioPlayer.playingMessage = null;
      this.audioPlayer.loading = false;
    },
    otherStop() {
      if (this.audioPlayer.innerAudioContext) {
        this.audioPlayer.innerAudioContext.pause();
        this.audioPlayer.loading = false;
        this.audioPlayer.playingMessage = null;
      }
    },
    initialAudioPlayer() {
      this.audioPlayer.innerAudioContext = document.createElement("audio");

      this.audioPlayer.innerAudioContext.addEventListener(
        "ended",
        this.audioPlayerOver,
        false
      );

      // this.audioPlayer.innerAudioContext = uni.createInnerAudioContext();
      // this.audioPlayer.innerAudioContext.onEnded(() => {
      //   this.audioPlayer.playingMessage = null;
      // });
      // this.audioPlayer.innerAudioContext.onStop(() => {
      //   this.audioPlayer.playingMessage = null;
      // });
    },
    // initRecorderListeners() {
    //   // 监听录音开始
    //   recorderManager.onStart(() => {
    //     this.audio.recording = true;
    //     this.audio.startTime = Date.now();
    //   });
    //   //录音结束后，发送
    //   recorderManager.onStop((res) => {
    //     let endTime = Date.now();
    //     this.audio.recording = false;
    //     let duration = endTime - this.audio.startTime;
    //     if (duration < 1000) {
    //       this.$notify({
    //         type: "danger",
    //         message: "录音时间太短",
    //         duration: 500,
    //       });
    //       return;
    //     }
    //     res.duration = duration;
    //     this.goEasy.im.createAudioMessage({
    //       to: this.to,
    //       file: res,
    //       notification: {
    //         title: this.doctor_name + "发来一段语音",
    //         body: "[语音消息]", // 字段最长 50 字符
    //       },
    //       onProgress: function (progress) {
    //         console.log(progress);
    //       },
    //       onSuccess: (message) => {
    //         console.log(message);
    //         this.sendMessage(message);
    //       },
    //       onFailed: (e) => {
    //         console.log("error :", e);
    //       },
    //     });
    //   });
    //   // 监听录音报错
    //   recorderManager.onError((res) => {
    //     this.audio.recording = false;
    //     recorderManager.stop();
    //     uni.showToast({
    //       icon: "none",
    //       title: "录音失败,请检查麦克风权限",
    //       duration: 1000,
    //     });
    //   });
    // },
    /**
     * 核心就是设置高度，产生明确占位
     *
     * 小  (宽度和高度都小于预设尺寸)
     *    设高=原始高度
     * 宽 (宽度>高度)
     *    高度= 根据宽度等比缩放
     * 窄  (宽度<高度)或方(宽度=高度)
     *    设高=MAX height
     *
     * @param width,height
     * @returns number
     */
    getImageHeight(width, height) {
      if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
        return height;
      } else if (width > height) {
        return (IMAGE_MAX_WIDTH / width) * height;
      } else if (width === height || width < height) {
        return IMAGE_MAX_HEIGHT;
      }
    },
    sendMessage(message) {
      message.payload.config = {
        appId: this.$store.state.appId,
        from: {
          id: this.doctor_id + "",
          name: this.doctor_name,
          avatar: this.avatar,
        },
        to: {
          id: this.friend.id + "",
          name: this.friend.name,
          avatar: this.friend.avatar,
        },
      };

      this.history.messages.push(message);
      this.scrollToBottom();
      this.goEasy.im.sendMessage({
        message: message,
        onSuccess: function (message) {
          console.log("发送成功.", message);
        },
        onFailed: function (error) {
          if (error.code === 507) {
            console.log(
              "发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss"
            );
          } else {
            console.log("发送失败:", error);
          }
        },
      });
    },
    sendTextMessage() {
      if (this.text.trim() !== "") {
        let body = this.text;
        if (this.text.length >= 50) {
          body = this.text.substring(0, 30) + "...";
        }
        this.goEasy.im.createTextMessage({
          text: this.text,
          to: this.to,
          notification: {
            title: this.doctor_name + "发来一段文字",
            body: body,
          },
          onSuccess: (message) => {
            this.sendMessage(message);
          },
          onFailed: (e) => {
            console.log("error :", e);
          },
        });
      }
      this.text = "";
    },
    sendVideoMessage() {
      uni.chooseVideo({
        success: (res) => {
          this.goEasy.im.createVideoMessage({
            to: this.to,
            file: res,
            notification: {
              title: this.doctor_name + "发来一个视频",
              body: "[视频消息]", // 字段最长 50 字符
            },
            onProgress: function (progress) {
              console.log(progress);
            },
            onSuccess: (message) => {
              this.otherTypesMessagePanelVisible = false;
              this.sendMessage(message);
            },
            onFailed: (e) => {
              console.log("error :", e);
            },
          });
        },
      });
    },
    beforeRead(file) {
      console.log(file);
      let files = [];
      let flag = false;
      if (!Array.isArray(file)) {
        files = [file];
      } else {
        files = file;
      }
      const types = ["image/jpeg", "image/png", "image/jpg"];
      files.find((v) => {
        if (!types.includes(v.type)) {
          this.$notify({ type: "warning", message: "请上传 jpg/png 格式图片" });
          flag = true;
          return true;
        }
      });
      if (flag) {
        return false;
      }
      this.sendImageMessage(files);
      return true;
    },
    sendImageMessage(files) {
      files.forEach((file) => {
        this.goEasy.im.createImageMessage({
          to: this.to,
          file: file,
          notification: {
            title: this.doctor_name + "发来一张图片",
            body: "[图片消息]", // 字段最长 50 字符
          },
          onProgress: function (progress) {
            console.log(progress);
          },
          onSuccess: (message) => {
            this.otherTypesMessagePanelVisible = false;
            console.log(message);
            message.payload.text = "[图片]"
            this.sendMessage(message);
          },
          onFailed: (e) => {
            console.log("error :", e);
          },
        });
      });
    },
    sendOrderMessage(order) {
      //GoEasyIM自定义消息,实现订单发送
      this.goEasy.im.createCustomMessage({
        type: "order",
        payload: order,
        to: this.to,
        notification: {
          title: this.doctor_name + "发来一个订单",
          body: "[订单消息]",
        },
        onSuccess: (message) => {
          this.otherTypesMessagePanelVisible = false;
          this.sendMessage(message);
        },
        onFailed: (e) => {
          console.log("error :", e);
        },
      });
      this.orderList.visible = false;
    },
    showActionPopup(message) {
      const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
      this.messageSelector.messages = [message];
      if (
        Date.now() - message.timestamp < MAX_RECALLABLE_TIME &&
        message.senderId == this.doctor_id &&
        message.status === "success"
      ) {
        this.actionPopup.recallable = true;
      } else {
        this.actionPopup.recallable = false;
      }
      this.actionPopup.visible = true;
    },
    hideActionPopup() {
      this.actionPopup.visible = false;
      this.actionPopup.message = null;
    },
    deleteSingleMessage() {
      this.$dialog
        .confirm({
          message: "确定要删除吗？",
        })
        .then((res) => {
          this.actionPopup.visible = false;
          if (res === "confirm") {
            this.deleteMessage();
          }
          // on confirm
        })
        .catch(() => {
          // on cancel
        });
    },
    deleteMultipleMessages() {
      if (this.messageSelector.messages.length > 0) {
        this.$dialog
          .confirm({
            message: "确定要删除吗？",
          })
          .then((res) => {
            this.messageSelector.visible = false;
            if (res === "confirm") {
              this.deleteMessage();
            }
            // on confirm
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    deleteMessage() {
      this.goEasy.im.deleteMessage({
        messages: this.messageSelector.messages,
        onSuccess: (result) => {
          this.messageSelector.messages.forEach((message) => {
            let index = this.history.messages.indexOf(message);
            if (index > -1) {
              this.history.messages.splice(index, 1);
            }
          });
          this.messageSelector.messages = [];
        },
        onFailed: (error) => {
          this.$notify({ type: "danger", message: "操作失败" });
          console.log("error:", error);
        },
      });
    },
    recallMessage() {
      this.actionPopup.visible = false;
      this.goEasy.im.recallMessage({
        messages: this.messageSelector.messages,
        onSuccess: () => {
          console.log("撤回成功");
        },
        onFailed: (error) => {
          console.log("撤回失败,error:", error);
        },
      });
    },
    editRecalledMessage(text) {
      if (this.audio.visible) {
        this.audio.visible = false;
      }
      this.text = text;
    },
    showCheckBox() {
      this.messageSelector.messages = [];
      this.messageSelector.visible = true;
      this.actionPopup.visible = false;
    },
    selectMessages(e) {
      console.log(e);
    },
    loadHistoryMessage(scrollToBottom) {
      //历史消息
      this.history.loading = true;
      let lastMessageTimeStamp = null;
      let lastMessage = this.history.messages[0];
      if (lastMessage) {
        lastMessageTimeStamp = lastMessage.timestamp;
      }
      this.goEasy.im.history({
        userId: this.friend.id,
        lastTimestamp: lastMessageTimeStamp,
        limit: 10,
        onSuccess: (result) => {
          this.history.loading = false;
          let messages = result.content;
          console.log(messages);
          if (messages.length === 0) {
            this.history.allLoaded = true;
          } else {
            if (lastMessageTimeStamp) {
              this.history.messages = messages.concat(this.history.messages);
            } else {
              this.history.messages = messages;
            }
            if (messages.length < 10) {
              this.history.allLoaded = true;
            }
            if (scrollToBottom) {
              this.scrollToBottom();
              //收到的消息设置为已读
              this.markPrivateMessageAsRead();
            }
          }
        },
        onFailed: (error) => {
          //获取失败
          console.log("获取历史消息失败:", error);
          // uni.stopPullDownRefresh();
          this.history.loading = false;
        },
      });
    },
    //语音录制按钮和键盘输入的切换
    switchAudioKeyboard() {
      if (!this.RecorderPermission) {
        Recorder.getPermission().then(
          () => {
            console.log("录音授权通过");
            this.RecorderPermission = true;
            this.audio.visible = !this.audio.visible;
          },
          (error) => {
            this.$dialog.alert({
              title: "提示",
              message: "请先允许该网页使用麦克风",
            });
            console.log(`${error.name} : ${error.message}`);
          }
        );
      } else {
        console.log("录音授权通过");
        this.audio.visible = !this.audio.visible;
      }

      // if (uni.authorize) {
      //   uni.authorize({
      //     scope: "scope.record",
      //     fail: () => {
      //       uni.showModal({
      //         title: "获取录音权限失败",
      //         content: "请先授权才能发送语音消息！",
      //       });
      //     },
      //   });
      // }
    },
    // 开始录音
    onRecordStart() {
      // 停止其他播放行为
      if (this.audio.recording) {
        // this.onRecordEnd();
        return;
      }
      this.otherStop();

      this.audio.recording = true;
      this.audio.startTime = Date.now();

      console.log("开始录音");
      this.Recorder = new Recorder({
        sampleBits: 8, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 11025, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1, // 声道，支持 1 或 2， 默认是1
        // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
      });
      this.Recorder.start(); // 开始录音
      clearTimeout(this.RecorderTimer);
      this.RecorderTimer = setTimeout(() => {
        this.$dialog.alert({
          title: "提示",
          message: "录音最长时间为60s",
        });
        this.onRecordEnd();
      }, this.RecorderTimes);

      // try {
      //   // 更多配置参考uniapp：https://uniapp.dcloud.net.cn/api/media/record-manager.html#getrecordermanager
      //   recorderManager.start({
      //     duration: 600000, // 指定录音的时长,单位 ms
      //   });
      // } catch (e) {
      //   uni.showModal({
      //     title: "录音错误",
      //     content:
      //       "请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档",
      //   });
      // }
    },
    // 录音结束
    onRecordEnd() {
      console.log("停止录音");
      this.audio.recording = false;
      clearTimeout(this.RecorderTimer);
      this.Recorder.stop();

      let endTime = Date.now();
      let duration = endTime - this.audio.startTime;
      if (duration < 1000) {
        this.$notify({
          type: "danger",
          message: "录音时间太短",
        });
        return;
      }

      // this.Recorder.pause(); // 暂停录音
      console.log("上传录音"); // 上传录音

      // const formData = new FormData()
      const blob = this.Recorder.getWAVBlob(); // 获取wav格式音频数据
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      const newbolb = new Blob([blob], { type: "audio/wav" });
      // console.log(newbolb);
      const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav", {
        type: newbolb.type,
        data: "789"
      });
      console.log(fileOfBlob);
      fileOfBlob.duration = duration;
      fileOfBlob.data = "123456";
      console.log(fileOfBlob);
      // formData.append('file', fileOfBlob)
      // const url = window.URL.createObjectURL(fileOfBlob)
      // this.src = url

      this.goEasy.im.createAudioMessage({
        to: this.to,
        file: fileOfBlob,
        notification: {
          title: this.doctor_name + "发来一段语音",
          body: "[语音消息]", // 字段最长 50 字符
        },
        onProgress: function (progress) {
          console.log(progress);
        },
        onSuccess: (message) => {
          console.log(message);
          message.payload.text = "[语音]"
          this.sendMessage(message);
        },
        onFailed: (e) => {
          console.log("error :", e);
        },
      });

      // try {
      //   recorderManager.stop();
      // } catch (e) {
      //   console.log(e);
      // }
    },
    showImageFullScreen(e) {
      console.log("图片浏览");
      ImagePreview([e]);
    },
    // playVideo(e) {
    //   this.videoPlayer.visible = true;
    //   this.videoPlayer.url = e.currentTarget.dataset.url;
    //   this.$nextTick(() => {
    //     this.videoPlayer.context.requestFullScreen({
    //       direction: 0,
    //     });
    //     this.videoPlayer.context.play();
    //   });
    // },
    playAudio(audioMessage) {
      let playingMessage = this.audioPlayer.playingMessage;

      if (playingMessage) {
        // this.audioPlayer.innerAudioContext.stop();
        // 如果点击的消息正在播放，就认为是停止播放操作
        if (playingMessage === audioMessage) {
          if (this.audioPlayer.loading) {
            this.audioPlayer.innerAudioContext.currentTime = 0;
            this.audioPlayer.innerAudioContext.play();
          } else {
            this.audioPlayer.innerAudioContext.pause();
          }
          this.audioPlayer.loading = !this.audioPlayer.loading;
          return;
        } else {
          this.audioPlayer.innerAudioContext.pause();
        }
      }
      this.audioPlayer.innerAudioContext.currentTime = 0;
      this.audioPlayer.playingMessage = audioMessage;
      this.audioPlayer.innerAudioContext.src = audioMessage.payload.url;
      this.audioPlayer.innerAudioContext.play();
      // this.audioPlayer.innerAudioContext.play();
    },
    onVideoFullScreenChange(e) {
      //当退出全屏播放时，隐藏播放器
      if (this.videoPlayer.visible && !e.detail.fullScreen) {
        this.videoPlayer.visible = false;
        this.videoPlayer.context.stop();
      }
    },
    messageInputFocusin() {
      this.otherTypesMessagePanelVisible = false;
      this.emoji.visible = false;
    },
    switchEmojiKeyboard() {
      this.emoji.visible = !this.emoji.visible;
      this.otherTypesMessagePanelVisible = false;
    },
    showOtherTypesMessagePanel() {
      this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
      this.emoji.visible = false;
    },
    chooseEmoji(emojiKey) {
      this.text += emojiKey;
    },
    showOrderMessageList() {
      this.orderList.orders = restApi.getOrderList();
      this.orderList.visible = true;
    },
    hideOrderMessageList() {
      this.orderList.visible = false;
    },
    scrollToBottom() {
      console.log("滚动到底部");
      this.$nextTick(() => {
        let ul = document.querySelector(".chatInterface");
        ul.scrollTo(0, ul.scrollHeight);
        ul = null;
      });
    },
    markPrivateMessageAsRead() {
      this.goEasy.im.markMessageAsRead({
        id: this.to.id,
        type: this.to.type,
        onSuccess: function () {
          console.log("标记私聊已读成功");
        },
        onFailed: function (error) {
          console.log("标记私聊已读失败", error);
        },
      });
    },
  },
};
</script>

<style scoped lang="scss" src="./im.scss"></style>
